﻿using Client.HttpHelp;
using Client.ICommandNotify;
using System;
using System.Collections.Generic;
using System.Drawing;
using System.Drawing.Printing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using static System.Drawing.Printing.PrinterSettings;

namespace Client.ViewModel.Material
{
    public class MaterialViewModel : NotifyBase
    {
        public  MaterialViewModel()
        {
            Selectcommand = new Command(ReverseDoExecute, ReverseCanExecute);
        }


        #region 方法
        private bool ReverseCanExecute()
        {
            if (string.IsNullOrWhiteSpace(DocumentNumber))
            {
                return false;
            }
            else
            {
                return true;
            }
        }

        private async void ReverseDoExecute(object obj)
        {
            var MysqlContext_ = HelpTools.IOC.Getobject<SqlServer.DbContextmysql>();
                MysqlContext_.SqlConfigstr = "";
            var DbContext_ = HelpTools.IOC.Getobject<SqlServer.DbContext>();
            var Dialog_ = HelpTools.IOC.Getobject<MessageDialog.Dialog>();
            string strconfig = HelpTools.IOC.Getobject<IConfiguration.IConfigurationHelp>().GetSetUpModel().Where(o => o.DatabaseName == Title)?.FirstOrDefault()?.ConnectingString;
            //修改本位币
            if ((obj as string) == "1")
            {     
                if (string.IsNullOrWhiteSpace(strconfig))
                {
                    Dialog_.OpenMessage("数据连接字符串为空,请检查数据库配置是否正确");
                    return;
                }
                DbContext_.SqlConfigstr = strconfig;
                if (DbContext_.Update($"UPDATE [dbo].[Settle_Clys] SET [CurrencyId] = '{SCDicValue}',SCDicValue='{SCDicValue}' WHERE BillNo='{DocumentNumber}'")>0)
                {
                    Dialog_.OpenMessage("修改成功");
                }
                else
                {
                    Dialog_.OpenMessage("修改失败");
                }
                return;
            }
            //修改税额
            if ((obj as string) == "2")
            {
                if (string.IsNullOrWhiteSpace(strconfig))
                {
                    Dialog_.OpenMessage("数据连接字符串为空,请检查数据库配置是否正确");
                    return;
                }
                DbContext_.SqlConfigstr = strconfig;
                if (string.IsNullOrWhiteSpace(SelectText1))
                {
                    WPFDevelopers.Minimal.Controls.MessageBox.Show("税额/税率必填", "消息", MessageBoxButton.OK, MessageBoxImage.Warning);
                    return;
                }
                if (DbContext_.Update($"UPDATE [dbo].[{SelectText}] SET [{SelectText1}] = '{TaxAmount}' WHERE BillNo='{DocumentNumber}'") > 0)
                {
                    WPFDevelopers.Minimal.Controls.MessageBox.Show("修改成功", "消息", MessageBoxButton.OK, MessageBoxImage.Information);
                    return;
                }
                else
                {
                    WPFDevelopers.Minimal.Controls.MessageBox.Show("修改失败", "消息", MessageBoxButton.OK, MessageBoxImage.Error);
                    return;
                }
            }
            //单据反写
            if ((obj as string) == "3")
            { 

                if (string.IsNullOrWhiteSpace(strconfig))
                {
                    Dialog_.OpenMessage("数据连接字符串为空,请检查数据库配置是否正确");
                    return;
                }
                DbContext_.SqlConfigstr = strconfig;
                Dialog_.OpenDialog = true;
                await Task.Delay(2000);
                var selctsata = await Task.Run(() =>
                {
                    return DbContext_.Where($"SELECT a.BillId, a.WorkId FROM {SelectText} a WHERE BillNo='{DocumentNumber}'").Select().Select(o =>
                    {
                        return new
                        {
                            BillId = o["BillId"].ToString(),
                            WorkId = o["WorkId"].ToString(),
                        };
                    }).FirstOrDefault();
                });
                if (string.IsNullOrWhiteSpace(selctsata?.BillId) || string.IsNullOrWhiteSpace(selctsata?.WorkId))
                {
                    Dialog_.OpenDialog = false;
                    Dialog_.OpenMessage("没有查询到单据数据");
                    return;
                }
                var Http_ = HelpTools.IOC.Getobject<Http>();
                Http_.Uir = "http://cpms_material.scrbg.com/json.rpc";
                Models.Http.ParameterModel parameterModel = new Models.Http.ParameterModel();
                parameterModel.@params = new
                {
                    Id = selctsata.BillId,
                    State = 2,
                    workId = selctsata.WorkId,
                    pass = true
                };
                parameterModel.method = $"SettleMaterial.{SelectText.Split("_")[1]}.AuditAfter";//AuditAfter
                ResponseData = await Http_.PostData(parameterModel, "", "application/json");
                Dialog_.OpenDialog = false;
                return;
            }
            //物资合并
            if ((obj as string) == "4")
            {

                if (string.IsNullOrWhiteSpace(strconfig))
                {
                    Dialog_.OpenMessage("数据连接字符串为空,请检查数据库配置是否正确");
                    return;
                }
                DbContext_.SqlConfigstr = strconfig;
                Dialog_.OpenDialog = true;
                //await Task.Delay(2000);
                var selctsata = await Task.Run(() =>
                {
                var SiteReceive= DbContext_.Where($"SELECT  * FROM [dbo].[Material_SiteReceive] WHERE [SourceNo] = '{DocumentNumber}' ").Select().Select(t =>
                    {
                        return new
                        {
                            BillId= t["BillId"].ToString(),
                            OrgId = t["OrgId"].ToString(),
                            StorageId= t["StorageId"].ToString(),
                            StorageName = t["StorageName"].ToString()
                        };
                    });
                    if (!SiteReceive.Any()) return null;
                    var storagelist = SiteReceive.GroupBy(o=>new
                    {
                        o.StorageName
                    }).OrderByDescending(t=>t.Count());
                    if(storagelist.Count()>1)
                    foreach (var item in storagelist)
                    {
                      var Stlist= item.GroupBy(o => new
                            {
                                o.StorageId
                            });
                            if (Stlist.Count() > 1)
                            {
                              var da=  WPFDevelopers.Minimal.Controls.MessageBox.Show("处理条件不满足 现场收料外包方单位Id有歧义 后续处理逻辑还没有更新,请手动处理,点击OK跳过此步骤,否则取消", "消息", MessageBoxButton.OK, MessageBoxImage.Information);
                                if (da == MessageBoxResult.OK)
                                {

                                }
                                else
                                {
                                    return null;
                                }
                                    MysqlContext_.SqlConfigstr = "";
                                    var iddata = MysqlContext_.Where($"SELECT a.id FROM outer_supplier a WHERE supplier_name = '{item.Key}' ").Select().Select(o => new
                                    {
                                        id = o["id"].ToString()
                                    }).FirstOrDefault();
                                    if (iddata != null && !string.IsNullOrWhiteSpace(iddata.id))
                                        foreach (var item1 in item)
                                        {
                                            if (iddata.id != item1.StorageId)
                                            {

                                            }
                                        }
                            }
                    }
                    return DbContext_.Where($"SELECT a.dtlid,b.StorageId, b.StorageName, b.SourceId, b.SourceNo, MatterId, MatterName, Spec, (Texture collate Chinese_PRC_CS_AS_WS) as Texture," +
                        $"MatterUnit, MatterUse, WareHouseId, WareHouseName, PurchaseUnitId, PurchaseUnitName, a.Number, a.CheckNumber, ReturnNumber, Price, Amount" +
                        $" FROM dbo.Material_SiteReceiveDtl a LEFT JOIN dbo.Material_SiteReceive b ON b.BillId = a.BillId " +
                        $"where BusinessType = 1 and Number > CheckNumber + ISNULL(ReturnNumber, 0)  AND  State = 2 AND OrgId = '{SiteReceive?.FirstOrDefault()?.OrgId}' AND SourceNo = '{DocumentNumber}' " +
                        $"and(OldBillId = '' OR OldBillId IS NULL)  AND  BillDate <= '2025-12-30' union all " +
                        $"SELECT  a.dtlid, b.ContractStorageId, b.StorageOtherName, b.SourceId, b.SourceNo, MatterId, MatterName, Spec, (Texture collate Chinese_PRC_CS_AS_WS) as Texture, " +
                        $" MatterUnit,MatterUse,WareHouseId,WareHouseName,PurchaseUnitId,PurchaseUnitName,a.Number,a.CheckNumber,ReturnNumber,Price,Amount " +
                        $"FROM dbo.Material_SiteReceiveDtl a LEFT JOIN dbo.Material_SiteReceive b ON b.BillId = a.BillId " +
                        $"where BusinessType = 5 and Number> CheckNumber + ISNULL(ReturnNumber, 0)  AND State = 2 AND OrgId = '{SiteReceive?.FirstOrDefault()?.OrgId}' AND SourceNo = '{DocumentNumber}' " +
                        $"AND SourceId<>'EstimatedNoId' and(OldBillId = '' OR OldBillId IS NULL)  AND BillDate<= '2025-12-30' ").Select().Select(o =>
                    {
                        return new
                        {
                            dtlid = o["dtlid"].ToString(),
                            StorageId = o["StorageId"].ToString(),
                            SourceNo = o["SourceNo"].ToString(),
                            SourceId = o["SourceId"].ToString(),
                            MatterId = o["MatterId"].ToString(),
                            MatterName = o["MatterName"].ToString(),
                            PurchaseUnitName = o["PurchaseUnitName"].ToString(),
                            Spec = o["Spec"].ToString(),
                            Texture = o["Texture"].ToString(),
                            MatterUnit = o["MatterUnit"].ToString(),
                            MatterUse = o["MatterUse"].ToString()
                        };
                    });
                });
                StringBuilder stringBuilder = new StringBuilder();
                StringBuilder stringBuilder1 = new StringBuilder();

                if(selctsata!=null)
                foreach (var item in selctsata?.GroupBy(o=>new {o.StorageId,o.SourceNo,o.SourceId,o.MatterId,o.MatterName}))
                {
                    if(item.Count() >= 2)
                    {
                       
                        foreach (var item1 in item)
                        {
                            stringBuilder.Clear();
                            if (string.IsNullOrWhiteSpace(item1.Spec))
                            {
                                stringBuilder.Append("Spec='',");

                            }
                            if (string.IsNullOrWhiteSpace(item1.Texture))
                            {
                                stringBuilder.Append("Texture='',");
                            }
                            if (string.IsNullOrWhiteSpace(item1.MatterUnit))
                            {
                                stringBuilder.Append("MatterUnit='',");
                            }
                            if (string.IsNullOrWhiteSpace(item1.MatterUse))
                            {
                                stringBuilder.Append("MatterUse=''");
                            }
                            string[] f = stringBuilder.ToString().Split(',');
                            try
                            {
                                if (f.Length == 1)
                                {
                                    DbContext_.Update($"UPDATE Material_SiteReceiveDtl SET {f[0]} WHERE DtlId='{item1.dtlid}'");
                                }
                                else
                                {
                                    DbContext_.Update($"UPDATE Material_SiteReceiveDtl SET {string.Join(",", f)} WHERE DtlId='{item1.dtlid}'");
                                }
                                if (string.IsNullOrWhiteSpace(item1.PurchaseUnitName))
                                {
                                  var adtadtl= DbContext_.Where($"SELECT Material_SiteReceiveDtl.BillId FROM Material_SiteReceiveDtl WHERE DtlId = '{item1.dtlid}' ").Select().Select(o =>
                                  {
                                      return new
                                      {
                                          BillId = o["BillId"].ToString(),                    
                                      };
                                  }).FirstOrDefault();
                                    var adtadtCBM = DbContext_.Where($"SELECT Material_SiteReceive.PurchaseUnitName,Material_SiteReceive.PurchaseUnitId FROM Material_SiteReceive WHERE [SourceNo] = '{DocumentNumber}'").Select().Select(o =>
                                    {
                                        return new
                                        {
                                            PurchaseUnitName = o["PurchaseUnitName"].ToString(),
                                            PurchaseUnitId = o["PurchaseUnitId"].ToString()
                                        };
                                    }).Where(t=>string.IsNullOrWhiteSpace(t.PurchaseUnitName)==false).FirstOrDefault();
                                    var adtadt2 = DbContext_.Update($"UPDATE Material_SiteReceive set PurchaseUnitName='{adtadtCBM.PurchaseUnitName}',PurchaseUnitId='{adtadtCBM.PurchaseUnitId}' WHERE BillId='{adtadtl.BillId}'");
                                }


                            }
                            catch (Exception ex)
                            {
                                stringBuilder1.Append($"{item1.MatterName} 合并失败 具体原因 {ex.Message}--");
                            }                         
                            stringBuilder1.Append($"{item1.MatterName} 合并完成 , ");
                        }
                    }
                    else
                    {

                    }
                }
                ResponseData = stringBuilder1.ToString();
                Dialog_.OpenDialog = false;
                return;
            }
            //内调结算差额修改为0
            if ((obj as string) == "5")
            {

                if (string.IsNullOrWhiteSpace(strconfig))
                {
                    Dialog_.OpenMessage("数据连接字符串为空,请检查数据库配置是否正确");
                    return;
                }
                DbContext_.SqlConfigstr = strconfig;
                Dialog_.OpenDialog = true;
                await Task.Delay(2000);
                if(DbContext_.Update($"UPDATE Settle_CljsNdjsDtl SET AmountDiff = 0 WHERE BillId IN (SELECT a.BillId from Settle_CljsNdjs a WHERE BillNo='{DocumentNumber}')") > 0)
                {
                    WPFDevelopers.Minimal.Controls.MessageBox.Show("修改成功", "消息", MessageBoxButton.OK, MessageBoxImage.Information);
                }
                else
                {
                    WPFDevelopers.Minimal.Controls.MessageBox.Show("修改失败", "消息", MessageBoxButton.OK, MessageBoxImage.Error);
                }

            }
            //材料结算差额修改为0
            if ((obj as string) == "6")
            {

                if (string.IsNullOrWhiteSpace(strconfig))
                {
                    Dialog_.OpenMessage("数据连接字符串为空,请检查数据库配置是否正确");
                    return;
                }
                DbContext_.SqlConfigstr = strconfig;
               // Dialog_.OpenDialog = true;
                var cljsdtl=   DbContext_.Where($"SELECT b.YsDtlId,b.FtYsTaxAmount,b.FtTaxAmount FROM Settle_Cljs a  JOIN Settle_CljsDtl b ON a.BillId=b.BillId WHERE a.BillNo='{DocumentNumber}' AND b.FtYsTaxAmount!=FtTaxAmount").Select().Select(o =>
                   new  {
                    YsDtlId=o["YsDtlId"].ToString(),
                    FtYsTaxAmount = o["FtYsTaxAmount"].ToString(),
                    FtTaxAmount = o["FtTaxAmount"].ToString()
                });
                if (cljsdtl!=null&& cljsdtl.Any())
                {
                    DbContext_.Update($"UPDATE Settle_CljsDtl SET FtYsTaxAmount=FtTaxAmount WHERE BillId in (SELECT BillId FROM Settle_Cljs WHERE BillNo='{DocumentNumber}')");
                    foreach (var item in cljsdtl)
                    {
                     DbContext_.Update($"UPDATE Settle_ClysDtl SET FtTaxAmount={item.FtTaxAmount}  WHERE DtlId='{item.YsDtlId}'");
                    }
                    WPFDevelopers.Minimal.Controls.MessageBox.Show("修改成功", "消息", MessageBoxButton.OK, MessageBoxImage.Information);
                }
                else
                {
                    WPFDevelopers.Minimal.Controls.MessageBox.Show("修改失败", "消息", MessageBoxButton.OK, MessageBoxImage.Error);
                }

            }
            //选不到现场发料领料人员
            if ((obj as string) == "7")
            {
                DbContext_.SqlConfigstr = strconfig;
                var xcfldata=  DbContext_.Where($"SELECT BillId,PickUnitId,PickUnitName,ContractId,OrgId FROM Material_SiteRelease WHERE BillNo = '{DocumentNumber}'").Select().Select(o =>
                {
                    return new
                    {
                        BillId=o["BillId"].ToString(),
                        PickUnitId = o["PickUnitId"].ToString(),
                        PickUnitName = o["PickUnitName"].ToString(),
                        ContractId = o["ContractId"].ToString(),
                        OrgId = o["OrgId"].ToString()
                    };
                }).FirstOrDefault();
                var sqlstr= HelpTools.IOC.Getobject<IConfiguration.IConfigurationHelp>().GetSetUpModel().Where(o => o.DatabaseName == "合同")?.FirstOrDefault()?.ConnectingString;
                if (string.IsNullOrWhiteSpace(sqlstr))
                {
                    WPFDevelopers.Minimal.Controls.MessageBox.Show("连接字符串不能为空", "消息", MessageBoxButton.OK, MessageBoxImage.Error);
                }
                DbContext_.SqlConfigstr = sqlstr;
                if (xcfldata == null||string.IsNullOrWhiteSpace(xcfldata.ContractId))
                {
                    WPFDevelopers.Minimal.Controls.MessageBox.Show("没有查询到单据", "消息", MessageBoxButton.OK, MessageBoxImage.Error);
                }
                var CBmdata = DbContext_.Where($"SELECT BName,BId FROM CBM_OtherContract WHERE BillId = '{xcfldata.ContractId}'").Select().Select(o =>
                {
                    return new
                    {
                        BName = o["BName"].ToString(),
                        BId = o["BId"].ToString()
                    };
                }).FirstOrDefault();
                if(CBmdata!=null&&xcfldata.PickUnitId == CBmdata.BId && xcfldata.PickUnitName == CBmdata.BName)
                {
                    DbContext_.SqlConfigstr = strconfig;
                    var Material_PartyBPersonList=  DbContext_.Where($"SELECT  BillId,BillNo,ID,Name,ParentId  FROM dbo.Material_PartyBPerson  WHERE  OrgId = '{xcfldata.OrgId}' AND State <> -1 and(Name like '%{xcfldata.PickUnitName}%' or ParentName like '%{xcfldata.PickUnitName}%')").Select().Select(o =>
                    {
                        return new
                        {
                            BillId=o["BillId"].ToString(),
                            BillNo = o["BillNo"].ToString(),
                            ID = o["ID"].ToString(),
                            Name = o["Name"].ToString(),
                            ParentId = o["ParentId"].ToString()
                        };
                    });
                    var mater = Material_PartyBPersonList.FirstOrDefault(t=>t.ParentId=="-1"&&t.Name== CBmdata.BName);
                    var Updatedtl = Material_PartyBPersonList.Where(o => o.ParentId==mater?.ID);
                    foreach (var item in Updatedtl)
                    {
                        DbContext_.Update($"update Material_PartyBPerson set ParentId = '{CBmdata.BId}'  where BillId = '{item.BillId}'");
                    }
                     DbContext_.Update($"update Material_PartyBPerson set ID = '{CBmdata.BId}'  where BillId = '{mater?.BillId}'");
                     WPFDevelopers.Minimal.Controls.MessageBox.Show("修改成功", "消息", MessageBoxButton.OK, MessageBoxImage.Information);
                    return;
                }
                else
                {

                }
            }
        }
        #endregion
        #region 命令
        //执行
        public Command Selectcommand { get; set; }
        #endregion
        #region 属性
        private string Title_ = "物资";
        //标题
        public string Title
        {
            get { return Title_; }
            set { Title_ = value; }
        }

        private string DocumentNumber_;

        public string DocumentNumber
        {
            get { return DocumentNumber_; }
            set { DocumentNumber_ = value; }
        }
        /// <summary>
        /// 本位币值
        /// </summary>
        private int SCDicValue_;

        public int SCDicValue
        {
            get { return SCDicValue_; }
            set { SCDicValue_ = value; }
        }
        /// <summary>
        /// 本位币字典
        /// </summary>
        private Dictionary<int,string> SCDicValueList_;

        public Dictionary<int,string> SCDicValueList
        {
            get {
                if(SCDicValueList_==null|| SCDicValueList_.Count == 0)
                {
                    SCDicValueList_ = new Dictionary<int, string>();
                    SCDicValueList_.Add(0, "人民币");
                    SCDicValueList_.Add(1, "美元");
                }
                return SCDicValueList_; 
            
            }
            set { SCDicValueList_ = value; }
        }
        private string ResponseData_;

        public string ResponseData
        {
            get { return ResponseData_; }
            set { ResponseData_ = value;
                SetProperty(ref ResponseData_, ResponseData);
            }
        }

        private Dictionary<string, string> DocumentType_;
        /// <summary>
        /// 单据类型选择
        /// </summary>
        public Dictionary<string, string> DocumentType
        {
            get
            {
                if (DocumentType_ == null || DocumentType_.Count == 0)
                {
                    DocumentType_ = new Dictionary<string, string>();
                    var IConfigurationHelp_ = HelpTools.IOC.Getobject<IConfiguration.IConfigurationHelp>();
                    foreach (var item in IConfigurationHelp_.GetSetUpTableModel().Where(t => t.ModuleName == Title_))
                    {
                        DocumentType_.Add(item.TableValue, item.TableName);
                    }
                    return DocumentType_;
                }
                else
                {
                    return DocumentType_;
                }
            }
            set { DocumentType_ = value; }
        }

        private Dictionary<string, string> DocumentType1_;
        /// <summary>
        /// 
        /// </summary>
        public Dictionary<string, string> DocumentType1
        {
            get
            {
                if (DocumentType1_ == null || DocumentType1_.Count == 0)
                {
                    DocumentType1_ = new Dictionary<string, string>();    
                    DocumentType1_.Add("TaxAmount", "税额");
                    DocumentType1_.Add("Tax", "税率");
                    DocumentType1_.Add("TaxSumAmount", "税价合计");
                    DocumentType1_.Add("SettleAmount","金额结算");
                    DocumentType1_.Add("Amount", "金额验收");
                    return DocumentType1_;
                }
                else
                {
                    return DocumentType1_;
                }
            }
            set { DocumentType1_ = value; }
        }
        private string SelectText_;
        /// <summary>
        /// 选中的类型数据
        /// </summary>
        public string SelectText
        {
            get { return SelectText_; }
            set { SelectText_ = value; }
        }
        private string SelectText1_;
        /// <summary>
        /// 
        /// </summary>
        public string SelectText1
        {
            get { return SelectText1_; }
            set { SelectText1_ = value; }
        }
        private string TaxAmount_;
        /// <summary>
        /// 
        /// </summary>
        public string TaxAmount
        {
            get { return TaxAmount_; }
            set { TaxAmount_ = value; }
        }
        #endregion
    }
}
